<template>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <div class="auto-create-watch-wrap">
                <el-form class="create-condition-form" label-width="180px" :model="createConditionForm" :rules="createConditionFormRules" ref="createConditionForm" @submit.native.prevent>
                    <el-form-item label="值班日期：" prop='watchTime'>
                        <el-date-picker
                            v-model="createConditionForm.watchTime"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd"
                            :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="轮班间隔（单位：天）：" prop='interval'>
                        <el-input type="number" v-model="createConditionForm.interval" placeholder="请输入轮班间隔（1~30）" :max="maxInterval" min="1"></el-input>
                    </el-form-item>
                </el-form>
                <el-row>
                    <el-button type="primary" @click.stop="handleChoosePerson" :disabled="haeChoosePerson">选择值班人员</el-button>
                </el-row>
                <el-row v-if="haeChoosePerson">
                    <el-form v-for="(obj, index) in shiftForm" :key="index" label-width="150px" :model="obj.watchInfo" :rules="shiftFormRules" ref="shiftForm" @submit.native.prevent>
                        <!-- 值班人员 -->
                        <el-form-item :label="'第'+obj.dayIndex+'天'+obj.watchInfo.watchClassName+'：'" prop='watchAccount'>
                            <el-select filterable multiple v-model="obj.watchInfo.watchAccount">
                                <el-option
                                    v-for="item in userList"
                                    :key="item.accountName"
                                    :label="item.name"
                                    :value="item.accountName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-row>
                <el-row class="verifyidentity-button">
                    <el-button @click.stop="closeFun" round>取消</el-button>
                    <el-button type="primary" @click="createWatchTable" :disabled="!haeChoosePerson" round>确定</el-button>
                </el-row>
                <!-- 生成的排班表弹框 -->
                <el-dialog
                    :close-on-click-modal="false"
                    v-loading="loading"
                    title="值班表预览"
                    width="900px"
                    top='10vh'
                    v-if="dialogPersonWatch"
                    :visible.sync="dialogPersonWatch"
                    @close="dialogPersonWatch = false"
                    append-to-body
                    v-dialogDrag>
                    <el-row class="user-info-form" type="flex" justify="center">
                        <el-col>
                            <el-table
                                :data="personWatchTable"
                                height="580">
                                <el-table-column label="序号" type="index" width="70"></el-table-column>
                                <el-table-column label="日期" prop="watchDate" :formatter="formatWatchDate" width="120"></el-table-column>
                                <el-table-column label="班次" prop="watchClassId" :formatter="mapClassesText" width="80"></el-table-column>
                                <el-table-column label="值班人" prop="watchAccount" :formatter="mapUserText" width="180"></el-table-column>
                                <el-table-column label="开始时间" prop="watchStartTime"></el-table-column>
                                <el-table-column label="结束时间" prop="watchEndTime"></el-table-column>
                            </el-table>
                            <el-row class="verifyidentity-button">
                                <el-button @click.stop="dialogPersonWatch=false" round>取消</el-button>
                                <el-button type="primary" @click="saveWatchPersonData" round>确定</el-button>
                            </el-row>
                        </el-col>
                    </el-row>
                </el-dialog>
            </div>
        </el-col>
    </el-row>
</template>
<script>
import utils from '@/utils/util'
import * as Dao from '@/api/watch'

let count = 0
export default {
    name: 'AutoCreatWatch',
    props: {
        organizationId: {
            required: true
        },
        userList: {
            required: true
        },
        classesInfo: {
            required: true
        },
        closeFun: {
            type: Function,
            required: true
        }
    },
    data() {
        let disabledDate = {
            disabledDate: (time) => {
                let nowData = new Date()
                nowData = new Date(nowData.setDate(nowData.getDate()))
                return time < nowData
            }
        }
        return {
            utils: utils,
            loading: false,
            dialogPersonWatch: false,
            haeChoosePerson: false,
            maxInterval: 30, // 最大轮班间隔
            pickerOptions: {
                disabledDate: (time) => {
                    let nowData = new Date()
                    nowData = new Date(nowData.setDate(nowData.getDate()))
                    return time < nowData
                }
            },
            // 创建值班条件表单
            createConditionForm: {
                watchTime: '',
                interval: ''
            },
            createConditionFormRules: {
                watchTime: [
                    { required: true, message: '请选择值班日期', trigger: 'change' },
                ],
                interval: [
                    { required: true, message: '请输入轮班间隔（1~30）', trigger: 'blur' },
                ],
            },
            // 值班天数
            days: 0,
            // 轮班人员分配填写表单
            shiftForm: [],
            shiftFormRules: {
                watchAccount: [
                    { required: true, message: '请选择值班人员', trigger: 'change' },
                ]
            },
            // 最终人员值班表
            personWatchTable: []
        }
    },
    created() {
        let that = this
        
    },
    methods: {
        formatWatchDate(row, column, cellValue, index) {
            if(cellValue) {
                let date = String(cellValue)
                return date.slice(0, 4) + '-' + date.slice(4, 6) + '-' + date.slice(6, 9)
            }else {
                return '-'
            }
        },
        // 日期增加X天
        addDate(date, days) {
            if (days == undefined || days === '') {
                days = 1
            }
            var currentDate = new Date(date);
            currentDate.setDate(currentDate.getDate() + days)
            var month = currentDate.getMonth() + 1
            var day = currentDate.getDate()
            return currentDate.getFullYear() + '-' + this.getFormatDate(month) + '-' + this.getFormatDate(day)
        },
        // 日期月份/天的显示，如果是1位数，则在前面加上'0'
        getFormatDate(arg) {
            if (arg == undefined || arg == '') {
                return ''
            }
            var re = arg + ''
            if (re.length < 2) {
                re = '0' + re
            }
            return re
        },
        // 选择值班人员
        handleChoosePerson() {
            let that = this
            let time = this.createConditionForm.watchTime
            let startTime = time[0]
            let watchDate = ''
            let newArr = []
            // 校验值班条件是否填写
            that.$refs['createConditionForm'].validate((valid) => {
                if(valid) {
                    // 班次是否设置
                    if (that.classesInfo.length > 0) {
                        // 生成轮班人员安排表单（根据轮班值循环）
                        for(var i=0, count=that.createConditionForm.interval; i < count; i++) {
                            // 班次循环
                            for(var j=0, len=that.classesInfo.length; j < len; j++) {
                                let obj = {
                                    watchAccount: [],
                                    watchAccountTxt: [],
                                    watchClassId: that.classesInfo[j].id,
                                    watchClassName: that.classesInfo[j].orderName
                                }
                                newArr.push({
                                    dayIndex: i+1,
                                    watchInfo: obj
                                })
                            }
                        }
                        that.shiftForm = newArr
                        that.haeChoosePerson = true
                    } else {
                        that.$message({
                            type: 'warning',
                            message: '请先设置班次'
                        })
                    }
                } else {
                    return false
                }
            })
        },
        mapUserText(row, column, cellValue, index) {
            let that = this
            let arr = cellValue.split(',')
            let newArr = []
            if(cellValue) {
                for(var i=0, len=arr.length; i < len; i++) {
                    let obj = {}
                    obj = that.userList.find((item)=>{
                        return item.accountName === arr[i]
                    });
                    newArr.push(obj.name)
                }
                return newArr.join('，')
            } else {
                return '-'
            }
        },
        mapClassesText(row, column, cellValue, index) {
            let that = this
            let obj = {}
            if(cellValue) {
                obj = that.classesInfo.find((item)=>{
                    return item.id === cellValue
                });
                return obj.orderName
            } else {
                return '-'
            }
        },
        // 生成值班表
        createWatchTable() {
            let that = this
            let multiLineFormValudate = true
            // 检测信息是否全部填写
            that.$refs['createConditionForm'].validate((valid1) => {
                if(valid1) {
                    // 检测轮值人员表
                    for(var n=0, len=that.$refs['shiftForm'].length; n < len; n++) {
                        that.$refs['shiftForm'][n].validate((valid2) => {
                            if(!valid2) {
                                multiLineFormValudate = false
                                return false
                            }
                        })
                    }
                    if(multiLineFormValudate) {
                        // 组装数据
                        that.personWatchTable = that.getWatchTableDate()

                        that.dialogPersonWatch = true
                    } else {
                        return false
                    }
                } else {
                    return false
                }
            })
        },
        // 值班数据组装
        getWatchTableDate() {
            let that = this
            let startDate = that.createConditionForm.watchTime[0] // 开始时间
            let shiftData = that.shiftForm // 轮班人员安排表数据
            let days = that.days // 安排值班天数
            let newArr = []

            for(var i=0; i < days; i++) {
                let index = i%that.createConditionForm.interval // 取轮班周期中的第几天
                let watchDate = that.addDate(startDate, i) // 值班日期
                for(var j=0, len=that.classesInfo.length; j < len; j++) {
                    let watchAccountList = shiftData[index*len+j].watchInfo.watchAccount
                    // 多个人员切分，每个人员生成一条记录
                    for(var k=0; k < watchAccountList.length; k++) {
                        let obj = {
                            id: 0,
                            organizationId: that.organizationId,
                            watchAccount: watchAccountList[k],
                            watchClassId: that.classesInfo[j].id,
                            watchDate: watchDate.split('-').join(''),
                            watchEndTime: that.addDate(watchDate, that.classesInfo[j].daysInterval) + ' ' + that.classesInfo[j].endTime + ':00', // 计算值班跨天
                            watchStartTime: watchDate + ' ' + that.classesInfo[j].startTime + ':00'
                        }
                        newArr.push(obj)
                    }
                }
            }
            return newArr
        },
        // 保存值班人员数据
        saveWatchPersonData() {
            let that = this
            let dataList = that.personWatchTable
            let successCount = 0

            for(var i=0, len=dataList.length; i < len; i++) {
                that.loading = true
                // 保存值班信息
                Dao.updateDetails(dataList[i]).then(res => {
                    if(res.status === 200) {
                        successCount += 1
                        // 全部提交完毕
                        if(successCount == dataList.length) {
                            // 移除遮罩
                            that.loading = false
                            that.$message({
                                message: '保存成功',
                                type: 'success'
                            })
                            // 关闭弹框
                            that.closeFun(true)
                        }
                    } else {
                        that.$message.error(res.info)
                        return false
                    }
                })
            }
        }
    },
    watch: {
        // 监听当前值班日期
        currentWatchTime(val, oldVal) {
            if(val !== oldVal) {
                let time = this.createConditionForm.watchTime
                let startTime = new Date(time[0])
                let endTime = new Date(time[1])
                // 隐藏轮班人员安排
                this.haeChoosePerson = false
                // 计算值班天数
                this.days = (time && time.length > 0) ? (Number((endTime.getTime() - startTime.getTime())/(1000*60*60*24)) + 1) : 0
                // 限制轮班间隔最大输入值
                if(this.days && Number(this.currentInterval) > this.days) {
                    this.createConditionForm.interval = this.days
                    this.$message.warning('轮班间隔最大值30天，且不能超过所选日期范围')
                }
            }
        },
        // 监听当前轮班间隔
        currentInterval(val, oldVal) {
            if(val !== oldVal) {
                // 隐藏轮班人员安排
                this.haeChoosePerson = false
                if(val > (this.days || 30)) {
                    this.createConditionForm.interval = (this.days || 30)
                    this.$message.warning('轮班间隔最大值30天，且不能超过所选日期范围')
                }
            }
        }
    },
    computed: {
        currentWatchTime() {
            return this.createConditionForm.watchTime
        },
        currentInterval() {
            return this.createConditionForm.interval
        }
    },
}
</script>
<style lang="scss">
.auto-create-watch-wrap {
    .create-condition-form {
        .el-date-editor {
            width: 100%;
        }
    }
}
</style>

